package com.sugon.api;

import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpUtil;
import com.sugon.annotation.IgnoreAuth;
import com.sugon.entity.ApiResult;
import com.sugon.entity.ApkVersionEntity;
import com.sugon.service.ApkVersionService;
import com.sugon.util.ApiBaseAction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(tags = "apk版本升级接口")
@RestController
@RequestMapping("/api/apkVersion")
public class ApiApkVersionController extends ApiBaseAction {

    @Autowired
    private ApkVersionService apkVersionService;

    /**
     * PAD端APP升级接口
     * @return
     */
    @ApiOperation(value = "PAD端APP升级接口")
    @IgnoreAuth
    @RequestMapping(value = "/loadVersion", method = RequestMethod.GET)
    public ApiResult<ApkVersionEntity> loadVersion() {
        ApiResult<ApkVersionEntity> apiResult = new ApiResult<>();
        ApkVersionEntity apkVersion = apkVersionService.loadByMaxVersion("PAD");
        return apiResult.success(apkVersion);
    }

    /**
     * apk版本升级接口
     * @param clientType 客户端类别
     * @return
     */
    @ApiOperation(value = "apk版本升级接口", notes = "用于PAD端和手机端获取最新版本信息")
    @IgnoreAuth
    @ApiImplicitParam(name = "clientType", value = "客户端类别", paramType = "query", dataType = "String", allowableValues = "PAD,MOBILE")
    @GetMapping("/update")
    public ApiResult<ApkVersionEntity> update(@RequestParam String clientType) {
        ApiResult<ApkVersionEntity> apiResult = new ApiResult<>();
        ApkVersionEntity apkVersion = apkVersionService.loadByMaxVersion(clientType);
        return apiResult.success(apkVersion);
    }

    /**
     * apk版本升级接口
     * @param apkVersionId APK版本ID
     * @param response 响应内容
     * @throws IOException
     */
    @ApiOperation(value = "apk版本升级接口", notes = "用于PAD端和手机端获取最新版本信息")
    @IgnoreAuth
    @ApiImplicitParam(name = "apkVersionId", value = "APK版本ID", paramType = "query", dataType = "String")
    @GetMapping("/download")
    public void download(@RequestParam String apkVersionId, HttpServletResponse response) throws IOException {
        ApkVersionEntity apkVersion = apkVersionService.queryObject(apkVersionId);
        Assert.notNull(apkVersion);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + apkVersion.getApkName() + "");
        HttpUtil.download(apkVersion.getUrl(), response.getOutputStream(), true);
    }

}
